package com.skytech.tax.customsdatawarehouse.singlewindow.customsagententrusted.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.customsagententrusted.domain.dao.EntrustedAgreementDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.customsagententrusted.domain.dao.EntrustedRelationDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.customsagententrusted.domain.entity.EntrustedAgreement;
import com.skytech.tax.customsdatawarehouse.singlewindow.customsagententrusted.domain.entity.EntrustedRelation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lianhong
 * @since 2022/6/15
 */
@Service
public class EntrustedRelationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EntrustedRelationService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private EntrustedRelationDao entrustedRelationDao;

    public void saveEntrustedRelation(String entrustedRelation) {
        if (StringUtils.isEmpty(entrustedRelation)) return;
        String entrustedRelationText = SecurityUtil.decrypt3DES(token, entrustedRelation);
        try {
            JSONObject entrustedRelationObj = JSON.parseObject(entrustedRelationText);
            if (entrustedRelationObj == null) return;
            String socialCreditCode = entrustedRelationObj.getString("socialCreditCode");
            JSONArray entrustedRelationArr = entrustedRelationObj.getJSONArray("entrustedRelations");
            if (CollectionUtils.isEmpty(entrustedRelationArr)) return;

            //委托协议列表拆分并存储
            List<EntrustedRelation> entrustedRelationList = new ArrayList<>();
            for (int i = 0; i < entrustedRelationArr.size(); i++) {
                JSONObject item = entrustedRelationArr.getJSONObject(i);
                EntrustedRelation relation = new EntrustedRelation(socialCreditCode, item);
                entrustedRelationList.add(relation);
            }
            if (CollectionUtils.isEmpty(entrustedRelationList)) return;

            this.deleteBySeqNo(entrustedRelationList.stream().map(EntrustedRelation::getSeqNo).collect(Collectors.toList()));

            entrustedRelationDao.save(entrustedRelationList);
        } catch (Exception e) {
            LOGGER.error("保存委托协议错误", e);
        }
    }

    private void deleteBySeqNo(List<String> seqNos) {
        entrustedRelationDao.deleteBy(seqNos);
    }
}
